#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "comm.chh"

int main()
{
    key_t key = GetKey();
    int shmid = GetShm(key);
    std::cout << "client: key:" << key << ", shmid:" << shmid << std::endl;

    // 虚拟地址空间挂接
    std::cout << "client: 开始将shm映射到虚拟地址空间!" << std::endl;
    char *s = (char *)shmat(shmid, nullptr, 0);
    std::cout << s << std::endl;
    // sleep(3);

    int wfd = open(filename.c_str(), O_WRONLY);
    if (wfd < 0)
    {
        std::cerr << "errno: " << errno << "errstring: " << strerror(errno) << std::endl;
        return 1;
    }

    // TODO
    char in = 'a';
    for (; in <= 'z'; in++)
    {
        s[in - 'a'] = in;
        sleep(4);
        int code = 1;
        write(wfd, &code, sizeof(code));
    }

    sleep(2);
    // 移除shm映射关系
    std::cout << "server:开始将shm从进程地址空间中移除" << std::endl;
    int shmrm = shmdt(s);
    if (shmrm == 0)
        std::cout << "client: 移除成功！" << std::endl;
    else
        std::cout << "client: 移除失败！" << std::endl;

    close(wfd);
    return 0;
}